<template>
  <div style="height: 100%">

    <ProductionDayB v-if="selectedData === 0" :key="selectedData"/>
    <productPlan v-if="selectedData === 3" :key="selectedData"/>
     <productTable v-if="selectedData === 2" :key="selectedData"/>
     <MonitorTree v-if="selectedData === 1" :key="selectedData"/>
  </div>
</template>

<script>
import ProductionDayB from './components/ProductionDayB.vue'
import productPlan from './components/productPlan.vue'
import productTable from './components/productTable.vue'
import MonitorTree from './components/MonitorTree.vue'
export default {
  components: { ProductionDayB,productPlan ,productTable,MonitorTree},
  name: "homeIndex",
  data() {
    return {
       selectedData: this.getInitialSelectedData(),
    }
  },
  created() {

  },
   mounted() {
    // 双重保障：同时监听storage事件和同页修改
    this.setupStorageListeners();
  },
  beforeDestroy() {
    this.removeStorageListeners();
  },
  methods: {
    getInitialSelectedData() {
      const storedVal = localStorage.getItem("selected");
      return storedVal ? Number(storedVal) : 0;
    },

    setupStorageListeners() {
      // 方案1：监听storage事件（跨标签页）
      window.addEventListener("storage", this.handleStorageChange);

      // 方案2：重写localStorage方法（同页修改）
      this.overrideLocalStorageMethods();
    },

    removeStorageListeners() {
      window.removeEventListener("storage", this.handleStorageChange);
    },

    handleStorageChange(event) {
      if (event.key === "selected") {
        this.updateSelectedData(event.newValue);
      }
    },

    overrideLocalStorageMethods() {
      const self = this;
      const originalSetItem = localStorage.setItem;

      // 重写setItem方法
      localStorage.setItem = function(key, value) {
        originalSetItem.apply(this, arguments);

        // 仅当修改selected时触发更新
        if (key === 'selected') {
          self.updateSelectedData(value);

          // 手动触发storage事件（兼容性处理）
          const event = new Event('storage');
          event.key = key;
          event.newValue = value;
          window.dispatchEvent(event);
        }
      };
    },

    updateSelectedData(newValue) {
      // 双重保障：使用Vue.set确保响应式更新
      this.$set(this, 'selectedData', Number(newValue) || 0);
    }
  }
}
</script>

<style scoped lang="scss">
/* 全局样式 */
.app-container {
  padding: 16px;
  background: #f5f5f5;
  height: 100%;
  box-sizing: border-box;


}
</style>
